package com.zst.dollars.handler.server;

import com.zst.dollars.common.Consts;
import com.zst.dollars.entity.msg.ClientMsgRequestMessage;
import com.zst.dollars.entity.msg.ServerMsgBoardcastMessage;
import com.zst.dollars.entity.msg.ServerMsgResponseMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 处理客户端发送过来的消息的转发,以及对客户端发送过来的消息的确认
 */
public class ClientMsgRequestHandler extends SimpleChannelInboundHandler<ClientMsgRequestMessage> {
    private ConcurrentHashMap<String, String> clientTokenUsernameMap;
    private ChannelGroup channelGroup;
    private static final Logger logger = LoggerFactory.getLogger(ClientMsgRequestMessage.class);

    public ClientMsgRequestHandler(ConcurrentHashMap<String, String> clientTokenUsernameMap, ChannelGroup channelGroup){
        this.clientTokenUsernameMap = clientTokenUsernameMap;
        this.channelGroup = channelGroup;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ClientMsgRequestMessage msg) throws Exception {
        logger.info("收到{}发送的消息：{}", clientTokenUsernameMap.get(msg.getClientToken()), msg.getMessage());
        //先广播消息
        ServerMsgBoardcastMessage boardcastMessage = new ServerMsgBoardcastMessage(
                clientTokenUsernameMap.get(msg.getClientToken()),
                msg.getMessage(),
                msg.getTimestamp()
        );
        final String clientToken = msg.getClientToken();
        channelGroup.stream().forEach(channel -> {
            if(!channel.attr(Consts.tokenKey).get().equals(clientToken)){
                logger.debug("发给{}的消息：{}", clientTokenUsernameMap.get(channel.attr(Consts.tokenKey).get()), boardcastMessage.getMessage());
                channel.writeAndFlush(boardcastMessage);
            }
        });

        //然后回复收到确认
        ServerMsgResponseMessage responseMessage = new ServerMsgResponseMessage();
        responseMessage.setSuccess(true);
        ctx.writeAndFlush(responseMessage);
    }
}
